<?php

namespace app\api\middleware;

use app\Request;
use Closure;

class AuthCheck
{
    public function handle(Request $request, Closure $next)
    {
        // 检查当前控制器是否设置了跳过认证
        if ($this->shouldSkipAuth($request)) {
            return $next($request);
        }

        // 检查用户是否登录
        if (!$this->isLogin($request)) {
            return json([
                'code' => 401,
                'msg' => '用户未登录',
                'data' => null
            ]);
        }

        return $next($request);
    }

    /**
     * 判断是否应该跳过认证
     *
     * @param Request $request
     * @return bool
     */
    private function shouldSkipAuth(Request $request)
    {
        $controller = $request->controller();
        $action = $request->action();

        try {
            $controllerClass = '\\app\\api\\controller\\' . $controller;
            if (class_exists($controllerClass)) {
                $controllerInstance = app($controllerClass);

                // 检查控制器是否有 shouldSkipAuth 方法
                if (method_exists($controllerInstance, 'shouldSkipAuth')) {
                    return $controllerInstance->shouldSkipAuth($action);
                }
            }
        } catch (\Exception $e) {
            // 记录错误但不中断认证流程
        }

        return false;
    }

    /**
     * 检查用户是否登录
     *
     * @param Request $request
     * @return bool
     */
    private function isLogin(Request $request)
    {
        return session('?user_id') || $request->header('Authorization');
    }
}
